<template>
	<div class="flex gap-2">
		<el-tag v-for="tag in dynamicTags" class="mr10" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)">
			{{ tag }}
		</el-tag>
		<el-input
			v-if="inputVisible"
			ref="InputRef"
			v-model="inputValue"
			class="w-20"
			size="small"
			@keyup.enter="handleInputConfirm"
			@blur="handleInputConfirm"
		/>
		<el-button v-else class="button-new-tag" size="small" @click="showInput"> + {{ defaultLabel }} </el-button>
	</div>
</template>
<script setup lang="ts" name="tagGroup">
import { watch, nextTick, ref, onMounted } from 'vue';
import { ElInput, ElMessage } from 'element-plus';

interface Props {
	modelValue: any[]; // 搜索参数
	defaultLabel?: string;
}
// // 默认值
let props = withDefaults(defineProps<Props>(), {
	modelValue: () => [],
	defaultLabel: '规格',
});

const emit = defineEmits(['update:modelValue', 'change']);

const inputValue = ref('');
const dynamicTags = ref(props.modelValue);

watch(
	() => dynamicTags,
	(val) => {
		emit('update:modelValue', val);
		emit('change', val);
	},
	{
		deep: true,
		immutable: true,
	}
);

watch(
	() => props.modelValue,
	(val) => {
		dynamicTags.value = val;
	},
	{
		deep: true,
		immutable: true,
	}
);

const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
	dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
	inputVisible.value = true;
	nextTick(() => {
		InputRef.value!.input!.focus();
	});
};

const handleInputConfirm = () => {
	const value = inputValue.value.trim();
	if (dynamicTags.value.includes(value)) {
		ElMessage.warning('不能重复添加');
		return;
	}
	if (value) {
		dynamicTags.value.push(value);
	}
	inputVisible.value = false;
	inputValue.value = '';
};
</script>
